//
//  XYTabBar.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 15/12/26.
//  Copyright © 2015年 cn.weibo. All rights reserved.
//

import UIKit

class XYTabBar: UITabBar {
    
    var didClickComposeBtnBlock:(() -> ())?
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        backgroundImage = UIImage(named: "tabbar_background")
        
        addSubview(composeBtn)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载按钮
    lazy private var composeBtn:UIButton = { () -> UIButton in
        
        let btn = UIButton()
        
        // 设置不同状态的背景
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        // 设置不同状态的图片
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        // 根据内容调整自身的大小
        btn.sizeToFit()
        
        btn.addTarget(self, action: "didClickComposeBtn", forControlEvents:.TouchUpInside)
        
        return btn
    }()
    
    @objc private func didClickComposeBtn() {
        
        didClickComposeBtnBlock?()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置按钮的frame
        composeBtn.center.x = self.bounds.size.width * 0.5
        composeBtn.center.y = self.bounds.size.height * 0.5
        // 便利其他子控件 调整frame
        let btnW = self.bounds.size.width * 0.2
        var index:CGFloat = 0
        for value in subviews{
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                value.frame.size.width = btnW
                value.frame.origin.x = index * btnW
                
                index++
                if index == 2 {
                    
                    index++
                }
                
            }
            
        }
        
    }
    

}
